package org.android;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.helloroad.Trip;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SearchTripView extends Activity {

	private AutoCompleteTextView departure;
	private AutoCompleteTextView arrival;
	private TextView dateTxv;
	private TextView dayTxv;
	private TextView timeTxv;
	private Button searchBtn;
	private Button dayBtn;
	private Button dateBtn;
	private Button timeBtn;
	private ArrayList<String> dayList;
	private ArrayList<String> locationsList;
	private HashMap<String, Boolean> selectedDayList;

	private List<Trip> searchResults;

	private static final int ACTIVITY_CREATE = 0;
	private static final int DATE_DIALOG_ID = 1;
	private static final int DAY_DIALOG_ID = 2;
	private static final int TIME_DIALOG_ID = 3;
	private static final int RESULTS_DIALOG_ID = 4;

	private int mYear;
	private int mMonth;
	private int mDay;

	private int mHour;
	private int mMinute;

	private int userId;

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateTimeDisplay();
		}
	};

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trip_search);

		Bundle extras = getIntent().getExtras();
		userId = extras.getInt("userId");

		departure = (AutoCompleteTextView) findViewById(R.id.departureSearch);
		arrival = (AutoCompleteTextView) findViewById(R.id.arrivalSearch);
		searchBtn = (Button) findViewById(R.id.tripSearch);
		dateTxv = (TextView) findViewById(R.id.dateDisplay);
		dayTxv = (TextView) findViewById(R.id.dayDisplay);
		timeTxv = (TextView) findViewById(R.id.timeDisplay);
		dayBtn = (Button) findViewById(R.id.dayChooser);
		dateBtn = (Button) findViewById(R.id.dateChooser);
		timeBtn = (Button) findViewById(R.id.timeChooser);

		locationsList = WSCommunicator.doGetLocations();
		ArrayAdapter adapter = new ArrayAdapter(this,
				android.R.layout.simple_dropdown_item_1line, locationsList
						.toArray());
		departure.setAdapter(adapter);
		arrival.setAdapter(adapter);

		selectedDayList = new HashMap<String, Boolean>();
		selectedDayList.put("monday", false);
		selectedDayList.put("tuesday", false);
		selectedDayList.put("wednesday", false);
		selectedDayList.put("thursday", false);
		selectedDayList.put("friday", false);
		selectedDayList.put("saturday", false);
		selectedDayList.put("sunday", false);

		dayList = new ArrayList<String>();
		dayList.add("monday");
		dayList.add("tuesday");
		dayList.add("wednesday");
		dayList.add("thursday");
		dayList.add("friday");
		dayList.add("saturday");
		dayList.add("sunday");

		// get the current date
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);

		dateBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		dayBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(DAY_DIALOG_ID);
			}
		});
		timeBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});
		searchBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String from = departure.getText().toString();
				String to = arrival.getText().toString();

				if (from.equals("")) {
					Toast.makeText(getBaseContext(), "Give the departure",
							Toast.LENGTH_SHORT).show();
				} else if (to.equals("")) {
					Toast.makeText(getBaseContext(), "Give the destination",
							Toast.LENGTH_SHORT).show();
				} else {
					String time = timeTxv.getText().toString();
					if (dateTxv.getVisibility() == TextView.VISIBLE)
						searchResults = WSCommunicator.search(from, to, dateTxv
								.getText().toString(), time);
					else
						searchResults = WSCommunicator.searchByDays(from, to,
								selectedDayList, time);
					if (searchResults.size() != 0)
						showDialog(RESULTS_DIALOG_ID);
				}
			}
		});
	}

	protected void updateDateDisplay() {
		for (String day : selectedDayList.keySet()) {
			selectedDayList.put(day, false);
		}
		dateTxv.setText(new StringBuilder().append(mMonth + 1).append("-")
				.append(
				mDay).append("-").append(mYear).append(" "));
		dayTxv.setText(null);
		dayTxv.setVisibility(TextView.INVISIBLE);
		dateTxv.setVisibility(TextView.VISIBLE);
	}

	protected void updateTimeDisplay() {
		timeTxv.setText(new StringBuilder().append(mHour).append(":").append(
				mMinute));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case DAY_DIALOG_ID:
			Dialog dayChooserDialog = createDayDialog();
			return dayChooserDialog;
		case TIME_DIALOG_ID:
			Dialog timeChooserDialog = new TimePickerDialog(this,
					mTimeSetListener, mHour, mMinute, true);
			return timeChooserDialog;
		case RESULTS_DIALOG_ID:
			Dialog resultsDialog = createResultsDialog();
			return resultsDialog;
		}
		return null;
	}

	protected void goToTripList() {
		Intent i = new Intent(this, TripListView.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}

	protected Dialog createDayDialog() {
		Dialog dayChooserDialog = new Dialog(this);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, dayList);
		ListView dayListView = new ListView(this);
		dayListView.setAdapter(adapter);
		OnItemClickListener listener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String day = ((TextView) view).getText().toString();
				if (selectedDayList.get(day) == false)
					selectedDayList.put(day, true);
				else
					selectedDayList.put(day, false);
				updateDayDisplay();
			}
		};
		dayListView.setOnItemClickListener(listener);
		dayChooserDialog.setContentView(dayListView);
		dayChooserDialog.setTitle("Day Frequency");
		return dayChooserDialog;
	}

	private Dialog createResultsDialog() {
		Dialog resultsDialog = new Dialog(this);
		ArrayAdapter<Trip> adapter = new ArrayAdapter<Trip>(this,
				android.R.layout.simple_list_item_1, searchResults);
		ListView searchResultsListView = new ListView(this);
		searchResultsListView.setAdapter(adapter);
		OnItemClickListener listener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Trip tripDetails = (Trip) parent.getItemAtPosition(position);
				goToTripInfo(tripDetails);
			}
		};
		searchResultsListView.setOnItemClickListener(listener);
		resultsDialog.setContentView(searchResultsListView);
		if (adapter.getCount() == 0 || adapter.getCount() == 1)
			resultsDialog.setTitle(String.valueOf(adapter.getCount())
					+ " result");
		else
			resultsDialog.setTitle(String.valueOf(adapter.getCount())
					+ " results");
		return resultsDialog;
	}

	protected void goToTripInfo(Trip tripDetails) {
		Intent i = new Intent(this, TripInfoView.class);
		i.putExtra("tripDetails", tripDetails);
		startActivityForResult(i, ACTIVITY_CREATE);
	}

	protected void updateDayDisplay() {
		StringBuilder str = new StringBuilder();
		for (String day : selectedDayList.keySet()) {
			if (selectedDayList.get(day) == true)
				str.append(day + ", ");
		}
		dayTxv.setText(str);
		dayTxv.setVisibility(TextView.VISIBLE);
		dateTxv.setText(null);
		dateTxv.setVisibility(TextView.INVISIBLE);
	}

	private void goToTrips() {
		Intent i = new Intent(this, TripListView.class);
		i.putExtra("userId", userId);
		startActivityForResult(i, ACTIVITY_CREATE);

	}
}
